<template>
  <div class="login">
    <form class="loginForm" action="#" method="post" @keyup.enter="props.title == 'LOGIN'? loginClick(): registerClick()
">
      <h1 class="login_title">{{ props.title }}</h1>
      <el-upload class="avatar-uploader" v-if="props.title === 'REGISTER'" :action="uploadUrl" :show-file-list="false"
        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
        <img v-if="loginFormDto.avatar" :src="loginFormDto.avatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <span class="up" v-if="props.title === 'REGISTER'">上传头像</span>
      <p>Username:<input id="username" v-model="loginFormDto.username" name="username" placeholder="请输入账号" type="text"
          maxlength="11"></p>

      <p>Password:<input id="password" v-model="loginFormDto.password" name="password" type="password"
          placeholder="请输入密码" autocomplete="off" maxlength="15"></p>

      <p v-if="props.title === 'REGISTER'">Email:<input id="email" v-model="loginFormDto.email" name="email"
          placeholder="请输入邮箱" type="email"></p>

      <p v-if="props.title === 'REGISTER'">Age:<input id="age" v-model="loginFormDto.age" name="age" placeholder="请输入年龄"
          type="number" max="100" min="0"></p>
      <span id="sex_span" v-if="props.title === 'REGISTER'">Sex：
        男<input class="sex" v-model="loginFormDto.sex" type="radio" name="sex" value="男" checked>
        女<input class="sex" v-model="loginFormDto.sex" type="radio" name="sex" value="女">
      </span>

      <p>验证码:<input type="text" v-model="loginFormDto.code" placeholder="请输入验证码"><img class="code" id="code"
          :src="getCodeUrl" @click="codeClick()">
      </p>

      <p v-if="props.title === 'LOGIN'">记住密码:<input id="remember" name="remember" type="checkbox">
        <a id="a_h" v-if="props.title === 'LOGIN'" href="">忘记密码？</a>
      </p>
      <div id="bt">
        <input class="login_submit" v-if="props.title === 'LOGIN'" name="register_submit" type="button" value="LOGIN"
          @click="loginClick">
        <input class="register_submit" type="button" value="REGISTER" @click="registerClick">
        <span class="g_login" v-if="props.title === 'REGISTER'" @click="emit('update:title', 'LOGIN')">Go to Login</span>
      </div>
    </form>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { User, AxiosResp } from '../../model/Model'
import type { UploadProps } from 'element-plus'
import { login, register } from '../../api/api'
import { useUserInfo } from '../../store/userInfo'
import router from '@/router/router'

const props = defineProps<{ title: string }>()
const emit = defineEmits(['update:title'])

const uploadUrl = ref(`${import.meta.env.VITE_BACKEND_API_BASE_URL}/users/upload`)
const getCodeUrl = ref(`${import.meta.env.VITE_BACKEND_API_BASE_URL}/users/getCode`)
const loginFormDto = ref<User>({
  'avatar': '',
  'username': '',
  'age': null,
  'sex': '男',
  'password': '',
  'email': '',
  'code': ''
})

// 登录
async function loginClick() {
  const resp: AxiosResp<string> = await login(loginFormDto.value)
  useUserInfo().token = resp.data.data
  codeClick()
  if (useUserInfo().token) {
    useUserInfo().getUserInfo(useUserInfo().getterToken)
    // 跳转主页
    router.push('/chat')
  }
}

// 注册
async function registerClick() {
  // 注册成功跳转登录页面
  if (props.title == 'REGISTER') {
    const resp: AxiosResp<string> = await register(loginFormDto.value)
    if (resp.data.code === 20051) {
      emit('update:title', 'LOGIN')
      resetLoginFormDto()
    }
  } else {
    emit("update:title", "REGISTER")
    resetLoginFormDto()
  }
  codeClick()
}

// 重置loginFormDto
function resetLoginFormDto() {
  loginFormDto.value = {
    'avatar': '',
    'username': '',
    'age': null,
    'sex': '男',
    'password': '',
    'email': '',
    'code': ''
  }
}

// 验证码点击更换
const codeClick = () => {
  getCodeUrl.value = `${import.meta.env.VITE_BACKEND_API_BASE_URL}/users/getCode`
  getCodeUrl.value = `${getCodeUrl.value}?${Math.random() * 1000}`
}

// 上传头像成功执行方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  loginFormDto.value.avatar = URL.createObjectURL(uploadFile.raw!)
}

// 上传头像之前执行方法
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error('Avatar picture must be JPG or Png format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.login {
  border: 0px solid;
  margin-left: 800px;
}

.loginForm {
  border: 1px solid transparent;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 15%;
  box-shadow: 5px 5px 0 0 rgba(0, 0, 0, 0.3);
  height: auto;
  width: 500px;
  padding-bottom: 10px;
}

.login_title {
  font-size: 30px;
  font-weight: bold;
  color: white;
  margin-left: 40px;
  margin-top: 5px
}

.up {
  font-size: 20px;
  color: wheat;
  margin-left: 210px;
  font-weight: bold;
}

p {
  font-size: 20px;
  margin-top: 30px;
  margin-left: 100px;
  color: azure;
}


input {
  margin-left: 15px;
  border-radius: 5px;
  border-style: hidden;
  height: 30px;
  width: 140px;
  background-color: rgba(216, 191, 216, 0.5);
  outline: none;
  color: #f0edf3;
  padding-left: 10px;
}

#username {
  width: 200px;
}

#password {
  width: 202px;
}

#bt {
  margin-left: 150px;
  margin-top: 20px;
  width: 300px;
}

.login_submit {
  width: 120px;
  height: 40px;
  border: 1px solid #333;
  border-radius: 10px;
  text-align: center;
  line-height: 40px;
  font-size: 16px;
  margin: 0px 0px 0px -30px;
  color: #fff;
  background-color: rgb(82, 103, 242);
  cursor: pointer;
  user-select: none;
  box-shadow: 1px 1px 5px 0px rgba(50, 50, 50, 0.75);
  transition: .2s;
}

.register_submit {
  width: 120px;
  height: 40px;
  border: 1px solid #333;
  border-radius: 10px;
  margin-left: 30px;
  text-align: center;
  line-height: 40px;
  font-size: 16px;
  color: #fff;
  background-color: rgb(82, 103, 242);
  cursor: pointer;
  user-select: none;
  box-shadow: 1px 1px 5px 0px rgba(50, 50, 50, 0.75);
  transition: .2s;
}

/* 按钮点击效果1 */
.register_submit .login_submit {
  transform: scale(1);
}

.register_submit:active {
  transform: scale(0.97);
}

.login_submit:active {
  transform: scale(0.97);
}

.g_login {
  text-decoration: underline;
  font-weight: bold;
  color: #ccc;
  cursor: pointer;
  margin-left: 30px;
}

#remember {
  margin-left: 15px;
  border-radius: 5px;
  border-style: hidden;
  background-color: rgba(216, 191, 216, 0.5);
  outline: none;
  padding-left: 10px;
  height: 20px;
  width: 20px;
}

#a_h {
  padding-left: 100px;
  color: red;
  text-decoration: none
}

.sex {
  height: 15px;
  width: 20px;
  margin-right: 10px;
}

#sex_span {
  font-size: 20px;
  color: white;
  margin-left: 100px;
}

#up {
  font-size: 20px;
  color: wheat;
  margin-left: 200px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}

input::-webkit-input-placeholder {
  color: #ccc;
  font-size: 16px;
}

.code {
  margin-left: 10px;
  margin-top: 1px;
  position: absolute;
  cursor: pointer;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin-left: 200px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>